//
//  MBEditProfileViewController.m
//  Meboo
//
//  Created by kyo on 2024/3/8.
//

#import "MBEditProfileViewController.h"
#import "MBPhotoManagerView.h"
#import "MBProfileNavView.h"
#import "MBProfileNameView.h"
#import "MBProfileAboutView.h"
#import "MBProfileInterestsView.h"
#import "KLInterestsModel.h"
@interface MBEditProfileViewController ()
@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic, strong) MBProfileNavView *navView;
@property (nonatomic , strong) MBPhotoManagerView *photoManagerView;
@property (nonatomic , strong) MBProfileNameView *nameView;
@property (nonatomic , strong) MBProfileAboutView *aboutView;
@property (nonatomic , strong) MBProfileInterestsView *interestsView;
@property (nonatomic , assign) BOOL isUpLoading;
@property (nonatomic , assign) NSInteger countNum;
@property (nonatomic , strong) UIScrollView *scrollView;
@property (nonatomic , strong) MBUserAccount *oldAccount;
//内容是否发生了改变
@property (nonatomic , assign) BOOL isChanged;
@end

@implementation MBEditProfileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HEXS(@"ffffff");
    [self setupNotification];
    [self setupUI];
    self.oldAccount = [MBUserAccount defaultAccount];
}

- (void)setupNotification {
    [MBNotificationCenter addObserver:self selector:@selector(uploadBegin) name:REGISTER_UPLOADPHOTO_BEGIN object:nil];
    [MBNotificationCenter addObserver:self selector:@selector(uploadEnd) name:REGISTER_UPLOADPHOTO_END object:nil];
    [MBNotificationCenter addObserver:self selector:@selector(uploadFail) name:REGISTER_UPLOADPHOTO_FAIL object:nil];
}

#pragma mark - Private Method
- (void)uploadBegin {
    self.isUpLoading = YES;
    self.countNum = 0;
    [NSTimer scheduledTimerWithTimeInterval:1
                                     target:self
                                   selector:@selector(startImageRotate:)
                                   userInfo:nil
                                    repeats:YES];
    [MBProgressHUD showActivityMessageInWindow:@"upLoading..."];
}

-(void)startImageRotate:(NSTimer *)timer {
    //30秒超时
    if (self.countNum == 30 && self.isUpLoading) {
        self.isUpLoading = NO;
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"time out"];
        [timer invalidate];
    } else if (!self.isUpLoading) {
        self.isUpLoading = NO;
        [timer invalidate];
    } else {
        self.countNum ++;
    }
}

- (void)uploadEnd {
    self.isUpLoading = NO;
    self.isChanged = YES;
    [MBProgressHUD hideHUD];
    [MBProgressHUD showSuccessMessage:@"upLoad success"];
}

- (void)uploadFail {
    self.isUpLoading = NO;
    [MBProgressHUD hideHUD];
    [MBProgressHUD showErrorMessage:@"upLoad fail"];
}

- (NSString *)removeSpaceWithString:(NSString *)string {
    //去除开头和结尾的空字符串
    NSCharacterSet *set = [NSCharacterSet whitespaceCharacterSet];
    NSString *trimmedString = [string stringByTrimmingCharactersInSet:set]; // 去除空格后的字符串
    NSLog(@"%@", trimmedString);
    return trimmedString;
}
#pragma mark - Action
- (void)saveProfile {
    self.navView.userInteractionEnabled =  NO;
    MBUserAccount  *account1 = [MBUserAccount defaultAccount];
    if (self.nameView.nameView.text.length > 30) {
        [MBProgressHUD showWarnMessage:@"nickName Support up to 30 characters!"];
        self.navView.userInteractionEnabled =  YES;
        return;
    } else if([self removeSpaceWithString:self.nameView.nameView.text].length == 0) {
        [MBProgressHUD showWarnMessage:@"nickName All Spaces are not supported!"];
        self.navView.userInteractionEnabled =  YES;
        return;
    }
    
    if (self.aboutView.aboutMeView.text.length > 500) {
        [MBProgressHUD showWarnMessage:@"aboutMe Support up to 500 characters!"];
        self.navView.userInteractionEnabled =  YES;
        return;
    }
    
//    [MBProgressHUD showActivityMessageInWindow:@"saving..."];
    //存储然后跳转
    NSMutableArray *codeArr = [NSMutableArray array];
    MBUserAccount  *account = [MBUserAccount defaultAccount];
    account.interests = [NSMutableArray array];
    for (KLInterestsModel *model in [MBMineDataManager  sharedManager].interestsArr) {
        if (model.selected) {
            [account.interests addObject:model.interest];
            [codeArr addObject:model.interestCode];
        }
    }
    account.nickName = self.nameView.nameView.text;
    account.aboutMe = self.aboutView.aboutMeView.text;
    
    [MBUserAccount  saveAccount:account];
    [[MBMineDataManager  sharedManager] saveUserInfoWithName:account.nickName about:account.aboutMe interests:codeArr Success:^(BOOL success) {
        [MBProgressHUD hideHUD];
        if (success) {
            [MBProgressHUD showSuccessMessage:@"Save Success"];
            [MBUserAccount  saveAccount:account];
        } else {
            [MBUserAccount  saveAccount:account1];
        }
        self.navView.userInteractionEnabled =  YES;
    }];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)checkChanged {
    if (![self.oldAccount.aboutMe isEqualToString:self.aboutView.aboutMeView.text] || ![self.oldAccount.nickName isEqualToString:self.nameView.nameView.text] || self.isChanged || ![self compareInterestsArray]) {
        return YES;
    }
    return NO;
}

- (BOOL)compareInterestsArray {
    NSMutableArray *newArr = [NSMutableArray array];
    for (KLInterestsModel *model in [MBMineDataManager  sharedManager].interestsArr) {
        if (model.selected) {
            [newArr addObject:model.interest];
        }
    }
    // 检查数组大小是否相同
     if (self.oldAccount.interests.count != newArr.count) {
         return NO;
     }
    
    // 比较数组元素是否相同
    for (NSUInteger i = 0; i < self.oldAccount.interests.count; i++) {
        if (![newArr containsObject:self.oldAccount.interests[i]]) {
            return NO;
        }
    }
    return YES;
}

- (void)changeAction {
    __WeakSelf
    //获取
    UIAlertController  *alert = [UIAlertController alertControllerWithTitle:nil message:@"Whether to save the modified information" preferredStyle:UIAlertControllerStyleAlert];
    if ([self getIsIpad]){
        alert.popoverPresentationController.sourceView = self.view;
        alert.popoverPresentationController.sourceRect = CGRectMake(ScreenWidth/2,ScreenHeight/2,0,0);
        alert.popoverPresentationController.permittedArrowDirections = 0;
    }
    
    UIAlertAction  *emailAction = [UIAlertAction actionWithTitle:@"Save" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf saveProfile];
    }];
    
    UIAlertAction  *cancelAction = [UIAlertAction actionWithTitle:@"Not Save" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [alert addAction:emailAction];
    [alert addAction:cancelAction];
    [self.currentViewController presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.navView];
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(StatusBarAndNavigationBarHeight);
    }];
    
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.navView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];
    
    [self.scrollView addSubview:self.photoManagerView];
    [self.photoManagerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(MBHeightScale(20));
        make.height.mas_equalTo(ScreenWidth-MBHeightScale(60)+MBHeightScale(32));
        make.left.mas_equalTo(MBWidthScale(30));
        make.width.mas_equalTo(ScreenWidth-MBWidthScale(60));
    }];
    
    [self.scrollView addSubview:self.nameView];
    [self.nameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.photoManagerView.mas_bottom).offset(20);
        make.left.mas_equalTo(MBWidthScale(30));
        make.width.mas_equalTo(ScreenWidth-MBWidthScale(60));
        make.height.mas_equalTo(MBHeightScale(108));
    }];
    
    [self.scrollView addSubview:self.aboutView];
    [self.aboutView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameView.mas_bottom).offset(20);
        make.left.mas_equalTo(MBWidthScale(30));
        make.width.mas_equalTo(ScreenWidth-MBWidthScale(60));
        make.height.mas_equalTo(MBHeightScale(108));
    }];
    
    [self.scrollView addSubview:self.interestsView];
    [self.interestsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.aboutView.mas_bottom).offset(20);
        make.left.mas_equalTo(MBWidthScale(30));
        make.width.mas_equalTo(ScreenWidth-MBWidthScale(60));
        make.height.mas_equalTo(MBHeightScale(292));
        make.bottom.mas_equalTo(MBHeightScale(-30));
    }];
}

#pragma mark - Setter && Getter
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
        _scrollView.backgroundColor = UIColor.clearColor;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

- (MBPhotoManagerView *)photoManagerView {
    if (!_photoManagerView) {
        _photoManagerView = [MBPhotoManagerView new];
        __WeakSelf
        _photoManagerView.photoSelectBlock = ^(NSMutableArray * _Nonnull imageArr, BOOL isDelete) {
            if (imageArr.count > 0) {
                MBUserAccount *account = [MBUserAccount defaultAccount];
                account.images = imageArr;
                account.avatarUrl = imageArr[0];
                
                [[MBMineDataManager  sharedManager] changeUserInfoWithKey:@"images" value:account.images Success:^(BOOL success) {
                    if (success) {
                        [MBUserAccount saveAccount:account];
                        if (!isDelete) {
                            [MBNotificationCenter postNotificationName:REGISTER_UPLOADPHOTO_END object:nil];
                        }
                    }
                }];
            }
        };
    }
    return _photoManagerView;
}

- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [UIImageView new];
        _backImageView.image = ImageWithName(@"home_back_image");
    }
    return _backImageView;
}

- (MBProfileNavView *)navView {
    if (!_navView) {
        __WeakSelf
        _navView = [MBProfileNavView new];
        _navView.rightBlock = ^{
            if ([weakSelf checkChanged]) {
                //有变化
                [weakSelf saveProfile];
            } else {
                [weakSelf.currentViewController.navigationController popViewControllerAnimated:YES];
            }
        };
        _navView.leftBlock = ^{
            if ([weakSelf checkChanged]) {
                //有变化
                [weakSelf changeAction];
            } else {
                [weakSelf.currentViewController.navigationController popViewControllerAnimated:YES];
            }
        };
    }
    return _navView;
}

- (MBProfileNameView *)nameView {
    if (!_nameView) {
        _nameView = [MBProfileNameView new];
    }
    return _nameView;
}

- (MBProfileAboutView *)aboutView {
    if (!_aboutView) {
        _aboutView = [MBProfileAboutView new];
    }
    return _aboutView;
}

- (MBProfileInterestsView *)interestsView {
    if (!_interestsView) {
        _interestsView = [MBProfileInterestsView new];
    }
    return _interestsView;
}
@end
